package com.siyougame.app.resolver;


import cn.dev33.satoken.stp.StpUtil;
import com.siyougame.app.WxUserEntity;
import com.siyougame.app.annotation.AppLoginUser;
import com.siyougame.app.annotation.NeedLogin;
import com.siyougame.app.annotation.NeedMobile;
import com.siyougame.app.service.ApiWxUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;


@Component
public class AppLoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Autowired
    private ApiWxUserService wxUserService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(WxUserEntity.class) && parameter.hasParameterAnnotation(AppLoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {

        Object object = StpUtil.getLoginIdDefaultNull();

        boolean needLogin = parameter.hasMethodAnnotation(NeedLogin.class) || parameter.getContainingClass().isAnnotationPresent(NeedLogin.class);
        boolean needMobile = parameter.hasMethodAnnotation(NeedMobile.class) || parameter.getContainingClass().isAnnotationPresent(NeedMobile.class);

        if (object == null) {
            if (needLogin&&object == null) {
                throw new RuntimeException("需要登陆才可以访问");
            }
            if (needMobile) {
                throw new RuntimeException("请先登陆");
            }
            return null;
        }


        //获取用户信息
        WxUserEntity wxUserEntity = wxUserService.getById((String) object);
        if (needMobile&& StringUtils.isBlank(wxUserEntity.getMobile())) {
            throw new RuntimeException("未获取到手机号");
        }
        return wxUserEntity;
    }
}
